﻿using System;
using System.Windows.Forms;

namespace LabyCLI
{
    public partial class frmFind : Form
    {
        Terminal frm = Terminal.Instance;

        public frmFind()
        {
            InitializeComponent();
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            HighlightText(frm.GetCurrentTerminal(), txtbox_Search.Text);
        }

        private void HighlightText(RichTextBox Window, string Trigger)
        {
            if (Trigger == "")
            {
                return;
            }

            int s_start = Window.SelectionStart, startIndex = 0, index;
            int resultsFound = 0;

            while ((index = Window.Text.IndexOf(Trigger, startIndex)) != -1)
            {
                Window.Select(index, Trigger.Length);

                bool wasNotProtected = false;

                if (Window.SelectionProtected == true)
                {
                    // We can't change the selection colors as long as they are protected.
                    Window.SelectionProtected = false;
                }
                else
                {
                    wasNotProtected = true;
                }

                if (Window.BackColor.GetBrightness() > 0.5)
                {
                    Window.SelectionBackColor = ControlPaint.DarkDark(Properties.Settings.Default.Terminal_BackgroundColor);
                    Window.SelectionColor = ControlPaint.LightLight(Properties.Settings.Default.Terminal_TextColor);
                }
                else
                {
                    Window.SelectionBackColor = ControlPaint.LightLight(Properties.Settings.Default.Terminal_BackgroundColor);
                    Window.SelectionColor = ControlPaint.DarkDark(Properties.Settings.Default.Terminal_TextColor);
                }

                if (!wasNotProtected)
                {
                    Window.SelectionProtected = true;
                }

                startIndex = index + Trigger.Length;
                resultsFound++;
            }

            Window.SelectionStart = s_start;
            Window.SelectionLength = 0;
            Window.SelectionColor = Properties.Settings.Default.Terminal_TextColor;
            Window.SelectionBackColor = Properties.Settings.Default.Terminal_BackgroundColor;

            MessageBox.Show(resultsFound + " results found.");
        }

        private void txtbox_Search_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                HighlightText(frm.GetCurrentTerminal(), txtbox_Search.Text);

                DialogResult = DialogResult.OK;
            }
            else if (e.KeyCode == Keys.Escape)
            {
                DialogResult = DialogResult.Cancel;
            }
        }
    }
}
